//跟进计划列表
var $followPlanLogTable = $('#followRecord');
//防止表头与表格不对齐
$(window).resize(function () {
    $followPlanLogTable.bootstrapTable('resetView');
});

$(function () {
    // 初始化日期选择控件
    $('#startDate').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    // 初始化日期选择控件
    $('#endDate').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });

    //初始化跟进记录列表
    followRecordList();

});

function selectTime(time){
    if (time == 'all') {
        $('.all').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("");
        followRecordList();
    }
    if (time == 'today') {
        $('.today').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $("#dateType").val("thisDay");
        followRecordList();
    }
    if (time == 'week') {
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisWeek");
        followRecordList();
    }
    if (time == 'month') {
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisMonth");
        followRecordList();
    }
    if (time == 'year') {
        $('.year').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisYear");
        followRecordList();
    }
}

function followRecordList() {
//先销毁表格
    $followPlanLogTable.bootstrapTable('destroy');
    $followPlanLogTable.bootstrapTable({
        classes: 'table table-bordered table-hover',
        url: '/internalTrainingManager/selectFollowRecordList',//请求地址
        method: 'POST',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: false,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'clueFollowId',
        idField: 'clueFollowId',
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'followId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'left', formatter: indexFormat,width:120},
            {title: '客户名称',field: 'customerName', align: 'left', valign: 'middle',width: 350},
            {title: '联系人', field: 'contactName', align: 'left', valign: 'middle',width:150},
            {title: '跟进时间', field: 'createTm', align: 'left', valign: 'middle',width:150, sortable: true},
            {title: '跟进详情', field: 'followDetail', align: 'left', valign: 'middle',width:150, sortable: true},
            // {title: '操作',field: 'operate',align: 'right',formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#orderTableList').css({
                minWidth: $('#orderTableList').width()
            }).colResizable({
                resizeMode: 'overflow',
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                disabledColumns: [0,11,],      // 禁止拖动的列
                postbackSafe: true,                                         // 刷新后保持拖动的宽度
                partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
                flush: true,
                minWidth: 80,
                /*onResize: function () {
                }*/
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/**
 * 导入框
 */
function showImportFollowModal() {
    $('#importFollowModal').modal('show');
}

/**
 * 下载模板
 */
function downFollowTemplate() {
    var url="/clueFollow/downTemplate";
    window.location.href=encodeURI(encodeURI(url));
}

function  customerDetail(customerId) {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '客户详情',
        url: "/front/user/customerManager/customerDetail?customerId=" + customerId
    },true);
}

/**
 * 我的客户(个人客户)--客户名称列点击事件(客户详情)
 * @param customerName
 * @param contactPersonPhone
 */
function contactNameDetail (customerName, contactPersonPhone, customerId) {
    var contactId = "";

    //查询联系人id,进行跳转
    $.ajax({
        url: '/contact/getCustomerIdAndContactNameAndAccountId',
        type: 'POST',
        dataType: "json",
        data: {
            customerId,
            contactName: customerName,
            contactInformation : contactPersonPhone,
            contactNature : '1'
        },
        success: (function (data) {
            if (data.code == "000000") {
                if (data.data.contactId != null) {
                    contactId = data.data.contactId;
                    parent.$(parent.document).data('multitabs').create({
                        iframe: true,
                        title: '联系人详情',
                        url: "/front/user/contactManager/contactDetail?contactId=" + contactId
                    },true);
                }else{
                    $.alert("数据有问题,请重试!");
                }
            } else {
                alert("操作失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });
}

/**
 * 点击联系人姓名跳转联系人详情页面
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function contactNameFormat(value, row, index) {
    if(row.followSource == 6 && row.personName){//一机多用联系人显示(直接从cp_clue_follow表获取)
        return '<span href="JavaScript:void(0);">'+row.personName+ '</span>';
    }else{
        if(value == null) {
            return '<span href="JavaScript:void(0);">-</span>';
        }else {
            return '<a href="JavaScript:void(0);" onclick=\'contactDetail(\"'+row.contactId+'")\'>'+value+'</a>';
        }
    }


}

function  contactDetail(contactId) {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '联系人详情',
        url: "/front/user/contactManager/contactDetail?contactId=" + contactId
    },true);
}


function searchOrderList(type) {
    $("#dateType").val("");
    if (type === 1) {//普通条件查询
        $followPlanLogTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams2});
        // 点击搜索重置表单并收起高级搜索 需传入高级搜索id #filterContent
        $('#filterContent').collapse('hide').on('hidden.bs.collapse', function () {
            resetOrderQueryParams('#filterContent');
        });
    } else if (type == 2) {//高级搜索条件查询
        $('#orderNumberMin').val('');
        $followPlanLogTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
    }
}

function tagFormat(value){
    if(value != null && value != ''){
        var valueList =  value.split(',');
        if(valueList.length>5){
            valueList = valueList.slice(0,5)
        }
        let html = '';
        $.each(valueList,function(index,item){
            html +=  '<span class="tags">'+ item +'</span>';
        });

        return html;
    }else if(value == null || value  == ''){
        return '-'
    }


}


function queryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.isAdmin = $.trim($('#qx').val());//权限
    //搜索条件
    params.customerName = $.trim($('#customerName').val());//客户名称
    params.contactName = $.trim($('#contactPerson').val());//联系人
    params.startDate = $.trim($('#startDate').val());//开始计划日期
    params.endDate = $.trim($('#endDate').val());//截止计划日期
    params.companyId = $.trim($('#companyName').val());//公司
    params.createPeopleName = $('#createPeopleName').val();//所属人
    params.dateType = $('#dateType').val();
    params.followWay = $('#followWay').val();
    return params;
}

function queryParams2(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.isAdmin = $.trim($('#qx').val());//权限
    //搜索条件
    params.customerName = $.trim($('#customerName').val());//客户名称
    params.dateType = $('#dateType').val();
    params.followType = $('#followType').val();
    return params;
}

//重置高级查询
function clearAllData() {
    $('#customerName2').val('');
    $('#contactPerson').val('');
    $('#startDate').val('');
    $('#endDate').val('');
    $('#createPeopleName').val('');
    $('#company').val('');
    $('#followWay').val('');

}
/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    let html = '';
    html += '<button class="btn btn-default" onclick="getFollowInfo(\''+row.clueFollowId+'\',\''+row.followWay+'\')">详情</button>';
    html += '</ul></div>';
    return html;
}

//跟进详情
function getFollowInfo(clueFollowId,followWay) {
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : "跟进详情",
        url : "/front/customerManager/customerFollowRecordDetail?followWay="+followWay+"&clueFollowId="+ clueFollowId
    }, true);
}


function indexFormat(value, row, index) {
    return index + 1;
}


// 跳转线上线下电话跟进   跟进方式：1-线上电话；2-拜访 3-微信 4-线下电话 5-邮箱 6-陪访
function goOnline(name) {
    var type = '';
    var title = '跟进';
    var source = '1';//从哪跳转到跟进页面（0：线索；1：客户）
    // 线上电话
    if (name == 'online') {
        type = "1";
        title = '客户跟进-线上电话';
    }
    // 拜访
    if (name == 'visit') {
        type = "2";
        title = '客户跟进-拜访';
    }
    // 微信
    if (name == 'WeChat') {
        type = "3";
        title = '客户跟进-微信交流';
    }
    // 线下电话
    if (name == 'offline') {
        type = "4";
        title = '客户跟进-线下电话';
    }
    // 电子邮件
    if (name == 'email') {
        type="5";
        title = '客户跟进-电子邮件';
    }
    // 陪访
    if (name == 'accompanyingVisit') {
        type = "6";
        title = '客户跟进-陪访';
    }
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : title,
        url : "/front/followPlanManager/clueFollow?type="+ type +"&source=" +source
    }, true);
}
